package org.seamon.management.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.seamon.management.pojo.dto.SmsRecordListDto;
import org.seamon.management.pojo.dto.SmsSendDto;
import org.seamon.management.pojo.dto.SmsTaskListDto;
import org.seamon.management.pojo.vo.SmsRecordListVo;
import org.seamon.management.pojo.vo.SmsTaskListVo;
import org.seamon.management.service.SmsRecordService;
import org.seamon.management.service.SmsTaskService;
import org.seamon.management.util.Result;
import org.seamon.management.util.aspect.Limit;
import org.seamon.management.util.aspect.Log;
import org.seamon.management.util.enums.BusinessTypeEnum;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author Simon
 */
@Slf4j
@RestController
@RequestMapping("/api/sms")
public class SmsController {

    @Resource
    private SmsTaskService smsTaskService;
    @Resource
    private SmsRecordService smsRecordService;

    @Limit(key = "sms_send", permitsPerSecond = 10, timeout = 60, timeunit = TimeUnit.SECONDS)
    @PreAuthorize("hasAuthority('sms:send')")
    @Log(title = "发送短信", businessType = BusinessTypeEnum.ADD)
    @PostMapping("/send")
    public Result<?> send(@RequestBody @Valid SmsSendDto dto) {
        log.info("发送短信：{}", dto);
        smsTaskService.send(dto);
        return Result.success();
    }

    @PreAuthorize("hasAuthority('sms:view')")
    @Log(title = "获取短信任务列表", businessType = BusinessTypeEnum.LIST)
    @PostMapping("/tasks")
    public Result<?> listTasks(@RequestBody SmsTaskListDto dto) {
        log.info("获取任务列表, 筛选条件：任务状态：{}, 开始时间：{}，结束时间：{}", dto.getStatus(), dto.getStartTime(), dto.getEndTime());
        log.info("第 {} 页，每页 {} 条", dto.getCurrent(), dto.getSize());
        Page<SmsTaskListVo> page = smsTaskService.list(dto);
        return Result.success(page);
    }

    @PreAuthorize("hasAuthority('sms:record')")
    @Log(title = "获取任务列表", businessType = BusinessTypeEnum.LIST)
    @PostMapping("/records")
    public Result<?> listRecords(@RequestBody SmsRecordListDto dto) {
        log.info("获取记录列表, 筛选条件：任务状态：{}", dto.getStatus());
        log.info("第 {} 页，每页 {} 条", dto.getCurrent(), dto.getSize());
        Page<SmsRecordListVo> page = smsRecordService.list(dto);
        return Result.success(page);
    }

    @Limit(key = "sms_retry", permitsPerSecond = 20, timeout = 60, timeunit = TimeUnit.SECONDS)
    @PreAuthorize("hasAuthority('sms:retry')")
    @Log(title = "重发短信", businessType = BusinessTypeEnum.UPDATE)
    @PostMapping("/retry/{taskId}")
    public Result<?> retry(@PathVariable Long taskId) {
        log.info("重新发送任务：{}", taskId);
        smsTaskService.retry(taskId);
        return Result.success();
    }
}
